package org.shangma.service.impl;

import io.seata.core.context.RootContext;
import org.shangma.common.Good;
import org.shangma.common.Order;
import org.shangma.common.OrderStatus;
import io.seata.spring.annotation.GlobalTransactional;
import org.shangma.feign.AccountFeignClient;
import org.shangma.feign.GoodFeignClient;
import org.shangma.feign.OrderFeignClient;
import org.shangma.service.BusinessService;
import org.shangma.util.Urls;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class BusinessServiceImpl implements BusinessService {

//    @Autowired
//    RestTemplate restTemplate;

    @Autowired
    AccountFeignClient accountFeignClient;
    @Autowired
    GoodFeignClient goodFeignClient;
    @Autowired
    OrderFeignClient orderFeignClient;

    @Override
    @GlobalTransactional
    public void placeOrder(int accountId, int goodId, int num) {
        System.out.println("是否在全局事务中：" + RootContext.inGlobalTransaction());
        System.out.println("事务id: " + RootContext.getXID());
        System.out.println("事务类型: " + RootContext.getBranchType());


        Good good = goodFeignClient.findById(goodId);
        //Good good = restTemplate.getForObject(String.format(Urls.GOOD_INFO,goodId),Good.class);
        double amount = good.getGoodPrice()*num;
        Order order = new Order();
        order.setGoodId(goodId);
        order.setAccountId(accountId);
        order.setGoodNum(num);
        order.setStatus(OrderStatus.CREATE.name());
        order.setOrderAmount(amount);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Order> httpEntity = new HttpEntity<>(order,httpHeaders);
        // 创建订单
        //restTemplate.postForObject(Urls.CEATE_ORDER,httpEntity,String.class);
        orderFeignClient.addOrder(order);
        // 减库存
        //restTemplate.put(String.format(Urls.REDUCE_STOCK,goodId,num),null);
        goodFeignClient.reduceStock(goodId,num);
        // 扣钱
        //restTemplate.put(String.format(Urls.REDUCE_MONEY, accountId,amount),null);
        accountFeignClient.reduceMoney(accountId,amount);

    }
}
